<?php 
class Cache {
	private $memcache = null; 
	private $timeOut = 86400;
	
	public function __construct() {
		$this->memcache = new Memcache;
		$memcacheHost = explode(';', MEMCACHED);
		if (count($memcacheHost) >=1 ) {
			foreach ($memcacheHost as $i => $v) {
				$memcacheHostArr = explode(':', $v);
				$this->memcache->addServer($memcacheHostArr[0], $memcacheHostArr[1]);
			}
		}
		return $this->memcache;
	} 

	public function getInstance(){
        return $this->memcache;
    }
    
    public function set($key, $value) {
    	$this->memcache->set($key, $value, MEMCACHE_COMPRESSED, $this->timeOut); //这个地方要商量一下。这个时间默认好不好
    }
    
    public function get($key) {
    	return $this->memcache->get($key);
    }
    
    public function delete($key) {
    	$this->memcache->delete($key);
	}
	
	public function flush() {
    	$this->memcache->flush();
	}
	
	public function releaseLock($memcache, $name) {
		$this->memcache->delete("lock_".$name);
	}
	
	public function getLock($memcache, $name, $secs = 60) {
		return $this->memcache->add("lock_".$name, 1, false, $secs);
	}
	
	public function setEvent($UserId, $eventmsg) {
		$events = $this->memcache->get("e_".$UserId);
		if (!$events) {
			$events = array($eventmsg);
		} else {
			array_push($events, $eventmsg);
		}
		$this->memcache->set("e_".$UserId, $events);
	}
	
	/* 这三个方法都是和游戏相关的，先放在这里 。
	function giveItemReward($memcache, $db, $num, $itemid, $uid) { 
		$m_mg_ls=getItemData($memcache, $db, $itemid);
		if(!$m_mg_ls)
		{
			return 0;
		}
		
		return giveItemReward2($memcache, $db, $num, $m_mg_ls, $uid);
	}
	
	function giveItemReward2($memcache, $db, $num, $m_item, $uid) {
		$itemid = $m_item['id'];
		$iid = 0;
		$query_my_mg=$db->query("select id,num from interior_goods where s_id='".$itemid."' and i_uid='".$uid."';");
		$my_mg=$db->fetch_array($query_my_mg);
		if ($my_mg && ($m_item['stack'] == 0 || $m_item['stack'] > $my_mg['num'])) {
			$iid=$my_mg['id'];
			$db->query("update interior_goods set num=(num+".$num.") where id='".$iid."'");
		}else {
			$db->query("insert into interior_goods (i_uid,s_id,i_style_num,i_state,i_level,num,item_xe_def,item_xe_att,item_ex_def,item_ex_att,item_en_def,item_en_att,item_command) 
			values ('".$uid."','".$m_item['id']."','".$m_item['s_stylenum']."','0','".$m_item['s_level']."','".$num."','".$m_item['item_xe_def']."','".$m_item['item_xe_att']."','".$m_item['item_ex_def']."','".$m_item['item_ex_att']."','".$m_item['item_en_def']."','".$m_item['item_en_att']."','".$m_item['item_command']."');");
			$iid=$db->insert_id();
		}
		
		return $iid;
	}
	
	function getItemData($memcache, $db, $id)
	{
		$base_result = $memcache->get("i_".$id);
		if(!$base_result)
		{
		  $query=$db->query("select * from m_goods where `id`='".$id."'");
		  $base_result = $db->fetch_array($query);
		  $memcache->set("i_".$id, $base_result);
		}
		return $base_result;
	}
	*/
	
	
}
?>